from openai import OpenAI
from .models import ModelConfig


def generate_completion(message):
    config = ModelConfig.get_enabled_config()

    if config is None:
        return '未接入大模型，请检查配置！'
    else:
        return _generate_completion_remote(message, config)


def _generate_completion_remote(messages, config):
    client = OpenAI(
        api_key=config.api_key,
        base_url=config.api_base_url,
    )

    try:
        response = client.chat.completions.create(
            model=config.model_name,
            messages=messages,  # Updated to use 'message'
            stream=False
        )
        return response.choices[0].message.content
    except Exception as e:
        return f"Error: {str(e)}"
